#include "mainwindow.h"
#include <QHBoxLayout>
#include <QFileDialog>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , edtFile(new QLineEdit ("/home/arv000/demo") )
    , btnFile(new QPushButton ("selef elf") )
    , labFile(new QLabel ("elf path:") )
    , btnDoWork(new QPushButton("do work"))
    , btnELFHeader(new QPushButton("ELF"))
    , btnELFSectionHeader(new QPushButton("Section Header"))
    , btnELFSegmentHeader(new QPushButton("Segment Header"))
    , stackWidget(new QStackedWidget(this))
    , ElfHeaderWidget(new ELFHeaderWIdget())
    , sectionHeaderWidget(new SectionHeaderWidget(this))
    , segmentHeaderWidget(new SegmentHeaderWidget(this))
    , elfread(new ELFRead())
{
    initUI();
    initConnect();
}

MainWindow::~MainWindow()
{

}

void MainWindow::initUI()
{
    QWidget *main = new QWidget(this);
    QVBoxLayout *mainLay = new QVBoxLayout();
    QHBoxLayout *selectFileLay = new QHBoxLayout();
    selectFileLay->addWidget(labFile);
    selectFileLay->addWidget(edtFile);
    selectFileLay->addWidget(btnFile);
    QHBoxLayout *btnLay = new QHBoxLayout();
    btnLay->addWidget(btnELFHeader);
    btnLay->addWidget(btnELFSectionHeader);
    btnLay->addWidget(btnELFSegmentHeader);

    mainLay->addLayout(selectFileLay);
    mainLay->addWidget(btnDoWork);
    mainLay->addLayout(btnLay);
    mainLay->addWidget(stackWidget);
    stackWidget->addWidget(ElfHeaderWidget);
    stackWidget->addWidget(sectionHeaderWidget);
    stackWidget->addWidget(segmentHeaderWidget);
    stackWidget->setCurrentIndex(0);
    main->setLayout(mainLay);
    setCentralWidget(main);
}

void MainWindow::initConnect()
{
    connect(btnFile,&QPushButton::clicked,this,&MainWindow::slotSelectFile);
    connect(btnDoWork,&QPushButton::clicked,this,&MainWindow::slotDoWork);
     connect(btnELFHeader,&QPushButton::clicked,this,&MainWindow::slotSelectELFHeaderWIdget);
    connect(btnELFSectionHeader,&QPushButton::clicked,this,&MainWindow::slotSectionHeaderWidget);
      connect(btnELFSegmentHeader,&QPushButton::clicked,this,&MainWindow::slotSegmentHeaderWidget);
}

void MainWindow::slotSelectFile()
{
    edtFile->setText(QFileDialog::getOpenFileName(this));
}

void MainWindow::slotDoWork()
{

    elfread->updateData(edtFile->text().toStdString());
    ELF_HEADER elfHeader = elfread->getHeaderInfo();
    std::vector<ELF_SHDR> elfSectionHeaders  =  elfread->ReadFileSectionHeader();
    std::vector<ELF_PHDR> elfProgramHeaders = elfread->getFileProgramHeader();
    ElfHeaderWidget->updateData(elfHeader);
    sectionHeaderWidget->updateData(elfread);
    segmentHeaderWidget->updateData(elfProgramHeaders);
}

void MainWindow::slotSelectELFHeaderWIdget()
{
    stackWidget->setCurrentIndex(0);
}

void MainWindow::slotSectionHeaderWidget()
{
    stackWidget->setCurrentIndex(1);
}

void MainWindow::slotSegmentHeaderWidget()
{
     stackWidget->setCurrentIndex(2);
}

